#include <fstream>
#include <random>
#include <thread>

#include <bthread/bthread.h>
#include <glog/logging.h>
#include <gtest/gtest.h>

#include "hawking/indexlib/index_config.pb.h"
#include "doc/document_creator.h"
#include "index/inverted_index/inverted_mem_indexer/inverted_mem_indexer.h"
#include "index/inverted_index/inverted_disk_indexer/inverted_disk_indexer.h"
#include "util/file_wrapper/file_wrapper.h"

using namespace hawking::indexlib;
std::uniform_int_distribution<int32_t> dis(1, 100);
std::default_random_engine e{std::random_device{}()};

DEFINE_uint32(write_count, 0, "for dump test");
std::unordered_map<DocId, DocId> old2new_map;

void* TermRead(void* arg) {
    InvertedDiskIndexer* inverted_disk_indexer = reinterpret_cast<InvertedDiskIndexer*>(arg);

    while (1) {
        int32_t fake_term = dis(e);
        std::string str = std::to_string(fake_term);
        uint64_t term_key = HashAlgorithm::HashString64(str.data(), str.length());

        hawking::util::ArenaWrapper arena_wrapper;
        SegmentContext segment_ctx(arena_wrapper);
        inverted_disk_indexer->Lookup(term_key, 2000, &segment_ctx);
        // LOG(INFO) << "read docs " << segment_ctx.RelateDocCount() << " of " << fake_term << " of term_key " << term_key;
        bthread_usleep(1 * 1000);
    }
    
    return nullptr;
}

TEST(inverted_test, read) {
    InvertedDiskIndexer inverted_disk_indexer;
    inverted_disk_indexer.Load("/tmp/inverted_test");

    std::vector<bthread_t> readers;
    readers.reserve(128);
    for (size_t idx = 0; idx < readers.capacity(); ++idx) {
        readers.emplace_back();
        bthread_start_background(&readers.back(), nullptr, TermRead, &inverted_disk_indexer);
    }

    for (auto reader : readers) {
        bthread_join(reader, nullptr);
    }
}

TEST(inverted_test, load) {
    InvertedDiskIndexer inverted_disk_indexer;
    inverted_disk_indexer.Load("/tmp/inverted_test");
}

int main(int argc, char* argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    ::google::ParseCommandLineFlags(&argc, &argv, true);
    srand(static_cast<unsigned>(time(0)));
    return RUN_ALL_TESTS();
}
